package com.aspire.boc.mms.wmf.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.aspire.boc.mms.gwcmp.util.GwcmpAdminUtil;
import com.aspire.boc.mms.wmf.cam.Group;
import com.aspire.boc.mms.wmf.model.Ext4JsTreeNode;
import com.aspire.boc.mms.wmf.model.ExtJsTreeNode;
import com.aspire.boc.mms.wmf.model.SecurityData;
import com.aspire.boc.mms.wmf.model.SecurityGroup;
import com.aspire.boc.mms.wmf.model.SecurityUser;
import com.aspire.boc.mms.wmf.permission.PermissionCacheService;
import com.aspire.boc.mms.wmf.service.PermissionService;
import com.aspire.boc.mms.wmf.util.ResourceTreeUtil;

import net.sf.json.JSONObject;

@Controller
public class GroupRoleAct extends BaseAct{
	
	private static Log log = LogFactory.getLog(GroupRoleAct.class);

	@RequestMapping(value = "/groupRole/index")
	public String index(HttpServletRequest request, HttpServletResponse response ,HttpSession session) {
		return "../views/wmf/grouprole/index.jsp";
	}
	
	/**
	 * 加载群组树
	 * @return
	 */
	@RequestMapping(value = "/groupRole/loadAuthGroupTree", produces = {"text/javascript;charset=UTF-8"} )
	@ResponseBody
	public String loadAuthGroupTree() {
		
		log.info(">>>>> operation: /groupRole/loadAuthGroupTree");
		//Set<Group> groups = CamUtil.getCacheGroups();
		SecurityData securityDataCache = permissionCacheService.getSecurityDataCache();
		List<SecurityGroup> groups = securityDataCache.getGroups();
		if(groups == null || groups.isEmpty()) {
			return "{}";
		}
		List<Integer> authroizedGroups = permissionService.getRoleAuthorizedGroupIds();
		List<Ext4JsTreeNode> allTreeNodeList = new ArrayList<Ext4JsTreeNode>(groups.size());
		//for(Group group : groups) {
		for(SecurityGroup group : groups) {
			Ext4JsTreeNode treeNode = convertGroup2Ext4jsTreeNode(group);
			if(authroizedGroups != null && !authroizedGroups.isEmpty()) {
				if(authroizedGroups.contains(treeNode.getResourceId())) {
					treeNode.setChecked(true);
				}
			}
			allTreeNodeList.add(treeNode);
		}
		JSONObject jsonTree = ResourceTreeUtil.assembleExt4JsTree(allTreeNodeList, 0);
		return jsonTree != null ? jsonTree.toString() : null;
	}
	
	/**
	 * {group_name=root, user_name=chenjianjun, 
	 * group_id=670, group_descr=系统根组, parent_group_id=0, 
	 * level_id=1, system_def=MMS_SOMP}
	 * @Title: loadGroupTree 
	 * @Description: TODO(加载组树) 
	 * @param pid
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/groupRole/loadGroupTree")
	public @ResponseBody List<ExtJsTreeNode> loadGroupTree(
			@RequestParam(value = "node", required = true) String pid,
			HttpServletRequest request, 
			HttpServletResponse response,
			HttpSession session) {
		log.info(">>>>>>> /groupRole/loadGroupTree");
		List<ExtJsTreeNode> nodes = new ArrayList<ExtJsTreeNode>();
		SecurityUser securityUser = (SecurityUser) request.getSession().getAttribute("securityUser");
		SecurityData securityDataCache = permissionCacheService.getSecurityDataCache();
		Map<String, List<SecurityGroup>> userGroupMap = securityDataCache.getUserGroupMap();
		List<SecurityGroup> groups = securityDataCache.getGroups();
		//系统管理员显示全部
		if(securityUser.isSystemAdmin()){
			 if("groupRoot".equals(pid)){
				 pid = "0";
			 }
			 
			 for(SecurityGroup group : groups){
				 if(String.valueOf(group.getParentId()).equals(pid)){
					ExtJsTreeNode node = new ExtJsTreeNode();
					node.setId(String.valueOf(group.getGid()));
					node.setPID(pid);
					node.setIsRoot(false);
					node.setText(group.getName());
					node.setEnname(group.getName());
					node.setQtip(group.getDesc());
					node.setExpanded(true);
					nodes.add(node);
				 }
			 }
		}else{
			//非系统管理员
			List<SecurityGroup> userGroups = userGroupMap.get(securityUser.getLoginName());
			 if("groupRoot".equals(pid)){
				 pid = "0";
			 }
			 for(SecurityGroup group : userGroups){
				 if(String.valueOf(group.getParentId()).equals(pid)){
					ExtJsTreeNode node = new ExtJsTreeNode();
					node.setId(String.valueOf(group.getGid()));
					node.setPID(pid);
					node.setIsRoot(false);
					node.setText(group.getName());
					node.setEnname(group.getName());
					node.setQtip(group.getDesc());
					node.setExpanded(true);
					node.setDisabled(true);
					nodes.add(node);
				 }
			 }
		}
		return nodes;
	}
	
/**
 * 
 * @Title: save 
 * @Description: TODO(这里用一句话描述这个方法的作用) 
 * @param roleid
 * @param groupid
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
	@RequestMapping(value = "/groupRole/save")
	public @ResponseBody Map<String,Object> save(
			@RequestParam(value = "roleid", required = true) String roleid,
			@RequestParam(value = "groupid", required = true) String groupid,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		log.info(">>>>>>>>  /groupRole/save   roleid:" + roleid + "--->groupid:" + groupid);
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			permissionService.insertGroupRole(groupid, roleid);
			result.put("success" , Boolean.valueOf(true));
		} catch (Exception e) {
			log.info(">>>>>>>>  /groupRole/save" + e);
			e.printStackTrace();
			result.put("failure", Boolean.valueOf(true));
			result.put("flag", Integer.valueOf(2));
			result.put("msg", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 删除组含角色关系
	 * @param groupId 组ID
	 * @param roleIds 角色ID集合
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/groupRole/destroy")
	public @ResponseBody Map<String,Object> destroy(
			@RequestParam(value = "groupId", required = true) String groupId,
			@RequestParam(value = "roleIds", required = true) String roleIds,
			HttpServletRequest request){
		
		RequestContext requestContext = new RequestContext(request);
		String operator = GwcmpAdminUtil.getLoginUserName(request);
		log.error("operator: "+operator+",operation: /groupRole/destroy, params[groupId: "+groupId+", roleIds: "+roleIds+"]");
		Map<String,Object> result = new HashMap<String,Object>();
		if(StringUtils.isBlank(groupId)) {
			result.put("failure", Boolean.TRUE);
			result.put("msg", requestContext.getMessage("common.error.paramError"));
			return result;
		}
		groupId = StringUtils.trim(groupId);
		List<String> roleIdList = Arrays.asList(StringUtils.replace(roleIds, " ", "").split(","));
		if(roleIdList == null || roleIdList.isEmpty()) {
			result.put("failure", Boolean.TRUE);
			result.put("msg", requestContext.getMessage("common.error.paramError"));
			return result;
		}
		try {
			permissionService.deleteWmfGroupRole(groupId, roleIdList);
			result.put("success" , Boolean.TRUE);
			log.error("operator: "+operator+",operation: /groupRole/destroy, params[groupId: "+groupId+", roleIds: "+roleIds+"], success to delete relations");
		} catch(Exception e) {
			result.put("failure", Boolean.TRUE);
			result.put("msg", requestContext.getMessage("common.error.systemError"));
			log.error("operator: "+operator+",operation: /groupRole/destroy, params[groupId: "+groupId+", roleIds: "+roleIds+"], fail to delete relations");
		}
		return result;
	}
	
	/**
	 * 转化群组对象为树节点
	 * @param group
	 * @return
	 */
	private Ext4JsTreeNode convertGroup2Ext4jsTreeNode(Group group) {
		
		Ext4JsTreeNode treeNode = new Ext4JsTreeNode();
		treeNode.setResourceId(group.getId());
		treeNode.setText(group.getName());
		treeNode.setExpanded(true);
		treeNode.setLeaf(true);
		treeNode.setParentResourceId(group.getParentId());
		return treeNode;
	}
	
	/**
	 * 转化群组对象为树节点
	 * @param group
	 * @return
	 */
	private Ext4JsTreeNode convertGroup2Ext4jsTreeNode(SecurityGroup group) {
		
		Ext4JsTreeNode treeNode = new Ext4JsTreeNode();
		treeNode.setResourceId(group.getGid());
		treeNode.setText(group.getName());
		treeNode.setExpanded(true);
		treeNode.setLeaf(true);
		treeNode.setParentResourceId(group.getParentId());
		return treeNode;
	}

	@Autowired
	private PermissionService permissionService;
	@Autowired
	private PermissionCacheService permissionCacheService;
	
	
//	 接口不通
//	 DefaultMutableTreeNode o = null;
//	 DefaultMutableTreeNode oo =  CamUtil.getGroupTree();
//	 if("groupRoot".equals(pid)){
//		 DefaultMutableTreeNode fo = (DefaultMutableTreeNode) oo.children().nextElement();
//		 HashMap<?, ?> map = (HashMap<?, ?>) fo.getUserObject();
//		 pid = String.valueOf(map.get("parent_group_id"));
//	 }
//	 Enumeration enumeration = oo.children();
//	 if("groupRoot".equals(pid)){
//		 DefaultMutableTreeNode fo = (DefaultMutableTreeNode) oo.children().nextElement();
//		 HashMap<?, ?> map = (HashMap<?, ?>) fo.getUserObject();
//		 pid = String.valueOf(map.get("parent_group_id"));
//	 }
//    while(enumeration.hasMoreElements()){
//   	 o = (DefaultMutableTreeNode) enumeration.nextElement();
//   	 HashMap<?, ?> map = (HashMap<?, ?>) o.getUserObject();
//   	 if(String.valueOf(map.get("parent_group_id")).equals(pid)){
//			node.setId(String.valueOf(map.get("group_id")));
//			node.setPID(String.valueOf(map.get("parent_group_id")));
//			node.setIsRoot(false);
//			node.setText((String)map.get("group_descr"));
//			node.setEnname((String)map.get("group_name"));
//			node.setQtip((String)map.get("group_name"));
//			node.setExpanded(true);
//			nodes.add(node);
//   	 }
//    }
}


